package com.itheima.controller;

import com.itheima.dto.DishDto;
import com.itheima.result.R;
import com.itheima.service.DishService;
import com.itheima.vo.DishListVo;
import com.itheima.vo.GetPageRes;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;

    @PostMapping
    public R<String> addDish(@RequestBody DishDto dto) {
        if (dto == null) {
            R.error("不能为空");
        }
        boolean res = dishService.addDish(dto);
        return res ? R.success("添加成功") : R.error("添加失败");
    }

    @PutMapping
    public R<String> modifyDish(@RequestBody DishDto dto) {
        if (dto == null) {
            R.error("不能为空");
        }
        boolean res = dishService.modifyDish(dto);
        return res ? R.success("修改成功") : R.error("修改失败");
    }

    @DeleteMapping
    public R<String> deleteDish(@RequestParam("ids") String ids) {
        String[] idarr = ids.split(",");
        boolean res = dishService.deleteDish(idarr);
        return res ? R.success("成功") : R.error("失败");
    }

    @GetMapping("/list")
    public R<List<DishListVo>> getDishList(@RequestParam("categoryId") String categoryId) {
        List<DishListVo> dishListVos = dishService.getDishList(categoryId);
        return R.success(dishListVos);
    }

    @GetMapping("/page")
    public R<GetPageRes> getDishPage(@RequestParam(value = "name", required = false) String name,
                                     @RequestParam(value = "page", defaultValue = "1") Integer page,
                                     @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize){
        List<DishListVo> dishListVos = dishService.getDishPage(name, page, pageSize);
        GetPageRes<DishListVo> getPageRes = new GetPageRes<>();
        getPageRes.setRecords(dishListVos);
        return R.success(getPageRes);
    }

    @GetMapping("/{id}")
    public R<DishDto> getDishById(@PathVariable("id") String id){
        DishDto dish = dishService.getDishById(id);
        return R.success(dish);
    }

    @PostMapping("/status/{status}")
    public R<String> modifyStatus(@PathVariable("status") Integer status,@RequestParam("ids") String ids){
        String[] idsarr = ids.split(",");
        boolean res = dishService.modifyStatus(status, idsarr);
        return res?R.success("成功"):R.error("失败");
    }

}
